package com.hulk.dryad.admin.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fujieid.jap.sso.JapMfa;
import com.fujieid.jap.sso.JapMfaService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.hulk.dryad.admin.api.vo.SysUserVO;
import com.hulk.dryad.admin.api.dto.UserExtDTO;
import com.hulk.dryad.admin.api.dto.UserInfoDTO;
import com.hulk.dryad.admin.api.vo.OtpVO;
import com.hulk.dryad.admin.api.dto.UserViewDTO;
import com.hulk.dryad.admin.controller.basic.IController;
import com.hulk.dryad.admin.mapstruct.SysUserStruct;
import com.hulk.dryad.admin.mapstruct.UserExtStruct;
import com.hulk.dryad.admin.mapstruct.UserViewStruct;
import com.hulk.dryad.admin.service.SysRoleService;
import com.hulk.dryad.admin.service.SysUserService;
import com.hulk.dryad.common.annotation.Idempotent;
import com.hulk.dryad.common.annotation.OperLog;
import com.hulk.dryad.common.annotation.PrintlnLog;
import com.hulk.dryad.common.component.DryadUser;
import com.hulk.dryad.common.component.R;
import com.hulk.dryad.common.constant.CommonConstants;
import com.hulk.dryad.common.constant.enums.ActionType;
import com.hulk.dryad.common.constant.enums.BEC;
import com.hulk.dryad.common.util.SecurityUtils;
import com.hulk.dryad.manage.provider.service.SysDeptService;
import com.hulk.dryad.persistence.entity.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author kim
 * @date 2018/12/16
 */
@ApiSort(4)
@Api(value = "user", tags = "用户管理模块")
@RestController
@RequiredArgsConstructor
@RequestMapping("/admin/user")
public class SysUserController implements IController {

	private final SysUserService userService;
	private final JapMfaService japMfaService;
	private final SysDeptService deptService;
	private final SysRoleService roleService;
	/**
	 * 获取指定用户全部信息
	 * @param username 用户名
	 * @return UserInfoDTO
	 */
	@ApiOperation(value = "user", notes = "获取指定用户全部信息")
	@ApiOperationSupport
	@PrintlnLog
	@GetMapping("/info/{username}")
	public R user(@PathVariable String username) {
        SysUserModel user = userService.getOne( Wrappers.<SysUserModel>query().lambda()
                .eq(SysUserModel::getUsername, username));
		if (user == null) {
			return R.failed(BEC.E_2015,String.format("用户信息为空 %s", username));
		}
		UserInfoModel model = userService.findUserInfo(user);;
		UserInfoDTO  dto = new UserInfoDTO();
		BeanUtils.copyProperties(model,dto);
		return R.ok(dto);
	}

	/**
	 * 通过ID查询用户信息
	 * @param id ID
	 * @return 用户信息
	 */
	@ApiOperation(value = "getUserById", notes = "通过ID查询用户信息")
	@ApiOperationSupport(order = 1)
	@PrintlnLog
	@GetMapping("/{id}")
	public R getUserById(@PathVariable Integer id) {
		UserViewModel model = userService.selectUserVoById(id);
		UserViewDTO vo = UserViewStruct.INSTANCE.from(model);
		return R.ok(vo);
	}

	/**
	 * 验证用户名是否存在
	 * @param username 用户名
	 * @return count
	 */
	@ApiOperation(value = "checkByUserName", notes = "验证用户名是否存在")
	@ApiOperationSupport(order = 9)
	@PrintlnLog
	@GetMapping("/name/{username}")
	public R checkByUserName(@PathVariable String username) {
		int count = userService.count(Wrappers.<SysUserModel>lambdaQuery().eq(SysUserModel::getUsername,username));
		if(count>0){
			return R.failed(BEC.E_1006,count);
		}
		return R.ok(count);
	}

	/**
	 * 分页查询用户
	 * @param page 参数集
	 * @param sysUserVO 查询参数列表
	 * @return IPage
	 */
	@ApiOperation(value = "getUserPage", notes = "分页查询用户")
	@ApiOperationSupport(order = 6)
	@PrintlnLog
	@GetMapping("/page")
	public R getUserPage(Page page, SysUserVO sysUserVO) {
		SysUserModel sysUserModel =SysUserStruct.INSTANCE.to(sysUserVO);
		Page<UserViewModel>  rpm = userService.getUsersWithRolePage(page, sysUserModel);
		Page<UserViewDTO> rpv = UserViewStruct.INSTANCE.from(rpm);
		return R.ok(rpv);
	}

	/**
	 * 添加用户
	 * @param extDTO 用户信息
	 * @return OtpVO
	 */
	@ApiOperation(value = "saveUser", notes = "添加用户")
	@ApiOperationSupport(order = 4)
	@Idempotent
	@OperLog(value ="添加用户",action = ActionType.ADD)
	@PostMapping
	@PreAuthorize("@pms.hasPermission('sys_user_add')")
	public R saveUser(@Valid @RequestBody UserExtDTO extDTO) {
		SysUserModel user = userService.getById(((DryadUser) SecurityUtils.getUser()).getId());
		if (!user.isRoot()) {
			List<Integer> ownDeptList = deptService.selectScope();
			if (!ownDeptList.contains(extDTO.getDeptId())) {
				return R.failed(BEC.E_1003);
			}
			List<Integer> ownRoleList = roleService.findRolesByUserId(user.getUserId()).stream().map(SysRoleModel::getRoleId).collect(Collectors.toList());
			boolean roleCheckPass = true;
			for (Integer roleId : extDTO.getRole()) {
				if (!ownRoleList.contains(roleId)) {
					roleCheckPass = false;
					break;
				}
			}
			if (!roleCheckPass) {
				return R.failed(BEC.E_1003);
			}
		}
		UserExtModel extModel =UserExtStruct.INSTANCE.to(extDTO);
		JapMfa japMfa = new JapMfa(japMfaService);
		String secretKey = japMfa.getAuthenticator().createCredentials().getKey();
		extDTO.setTotp(secretKey);
		boolean saveSuccess = userService.saveUser(extModel);
		if (saveSuccess) {
			String otpQrCodeBase64 = japMfa.getOtpQrcodeFileBase64(extDTO.getUsername(), CommonConstants.BACK_END_PROJECT, true);
			OtpVO otpVo = new OtpVO();
			otpVo.setTotp(secretKey);
			otpVo.setImg(otpQrCodeBase64);
			return R.ok(otpVo);
		}
		return R.failed();
	}

	/**
	 * 更新用户信息
	 * @param extDTO 用户信息
	 * @return boolean
	 */
	@ApiOperation(value = "updateUser", notes = "更新用户信息")
	@ApiOperationSupport(order = 5)
	@Idempotent
	@OperLog(value ="更新用户信息",action = ActionType.UPDATE)
	@PutMapping
	@PreAuthorize("@pms.hasPermission('sys_user_edit')")
	public R updateUser(@Valid @RequestBody UserExtDTO extDTO) {
		UserExtModel extModel =UserExtStruct.INSTANCE.to(extDTO);
		boolean flag =userService.updateUser(extModel);
		return R.ok(flag);
	}

	/**
	 * 修改个人信息
	 * @param extDTO 实体
	 * @return boolean
	 */
	@ApiOperation(value = "updateUserInfo", notes = "修改个人信息")
	@ApiOperationSupport(order = 7)
	@Idempotent
	@OperLog(value ="修改个人信息",action = ActionType.UPDATE)
	@PutMapping("/edit")
	@PreAuthorize("@pms.hasPermission('sys_user_edit')")
	public R updateUserInfo(@Valid @RequestBody UserExtDTO extDTO) {
		UserExtStruct INSTANCE = UserExtStruct.INSTANCE;
		UserExtModel extModel = INSTANCE.to(extDTO);
		boolean flag = userService.updateUserInfo(extModel);
		return R.ok(flag);
	}

	/**
	 * 获取上级部门用户列表
	 * @param username 用户名称
	 * @return 上级部门用户列表
	 */

	@ApiOperation(value = "listAncestorUsers", notes = "获取上级部门用户列表")
	@ApiOperationSupport(order = 8)
	@PrintlnLog
	@GetMapping("/ancestor/{username}")
	public R listAncestorUsers(@PathVariable String username) {
		List<SysUserModel>  models = userService.listAncestorUsers(username);
		List<SysUserVO> dtos = SysUserStruct.INSTANCE.from(models);
		return R.ok(dtos);
	}

	/**
	 * 删除用户信息
	 * @param id ID
	 * @return boolean
	 */
	@ApiOperation(value = "removeUserById", notes = "根据ID删除用户")
	@ApiOperationSupport(order = 3)
	@Idempotent
	@OperLog(value ="删除用户信息",action = ActionType.DEL)
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('sys_user_del')")
	@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "int", paramType = "path")
	public R removeUserById(@PathVariable Integer id) {
		SysUserModel sysUser = userService.getById(id);
		boolean flag = userService.removeUserById(sysUser);
		return R.ok(flag);
	}
}
